<template>
	<view class="container">
		<view class="homeBg">
			<view @tap="back" class="icon-left">
				<u-icon name="arrow-left" color="#fff" size="16"></u-icon>
			</view>
			<view class="title">详情</view>
			<!-- <image src="../../static/home/search.png" mode="widthFix" class="searchIcon"></image> -->
		</view>
		<view class="billInfo">
			<view class="issues">积分代码：{{billInfo.billCode||''}}</view>
			<view class="issues">积分名称：{{billInfo.billName||''}}</view>
			<view class="issues">发行价：{{billInfo.issuesPrice||'0.00'}}元/个</view>
			<view class="issues">发行总量：{{parseInt(billInfo.issuesNumber)||'0'}}个</view>
			<view class="price">
				<view class="price-item">
					<view class="">当天开盘价</view>
					<view class="priceNum">{{infoData.priceOpen||'0.00'}}</view>
				</view>
				<view class="price-item active">
					<view class="">当天最高价</view>
					<view class="priceNum">{{infoData.priceHigh||'0.00'}}</view>
				</view>
			</view>
			<view class="quotation">
				<view class="quotation-item">
					<view class="label">涨跌幅</view>
					<view class="value">{{infoData.range||'0.00'}}%</view>
				</view>
				<!-- 				<view class="quotation-item">
					<view class="label">24H撮合量</view>
					<view class="value">0</view>
				</view>
				<view class="quotation-item">
					<view class="label">24H撮合额</view>
					<view class="value">20000</view>
				</view> -->
				<view class="quotation-item">
					<view class="label">当天最低价</view>
					<view class="value">{{infoData.priceLow||'0.00'}}</view>
				</view>
			</view>
		</view>
		<view class="line"></view>
		<view class="situation">
			<view class="top">
				<view class="">￥{{infoData.priceHigh||'0.00'}}</view>
				<view class="">
					<view class="">高<span>￥{{infoData.priceHigh||'0.00'}}</span></view>
					<view class="">低<span>￥{{infoData.priceLow||'0.00'}}</span></view>
				</view>
			</view>
			<view class="bottom">
				<view class="">{{infoData.range||'0.00'}}%</view>
				<view class="">24H {{parseInt(infoData.h24COunt)||'0.00'}}</view>
			</view>
		</view>
		<view class="label">
			<view class="label-item" :class="index == selectIndex ? 'activeClass': ''" v-for="(item,index) in labelList"
				:key="index" @tap="changeData(index)">{{item.label}}</view>
		</view>
		<canvas canvas-id="kuKIifblofRczsEzZJYCFwSgPaTVnfqc" id="kuKIifblofRczsEzZJYCFwSgPaTVnfqc" class="charts"
			@touchstart="touchstart" @touchmove="touchmove" @touchend="touchend" />
		<view class="enterpriseInfo">
			<view class="topTab">
				<u-tabs :list="tabList"
					itemStyle="height:72upx;flex:1;display:flex;align-items: center;justify-content: center;"
					:current="swiperCurrent" @change="tabsChange"></u-tabs>
			</view>
			<view class="bottomContent">
				<view class="contentItem" v-if="swiperCurrent == 0">
					<view class="tabLabel">
						<view class="label-item">序号</view>
						<view class="label-item">类型</view>
						<view class="label-item">数量</view>
						<view class="label-item">价格</view>
						<view class="label-item" style="flex: 3;">时间</view>
					</view>
					<view v-if="dealList.length>0">
						<view class="tabLabel tabLabel1" v-for="(item,index) in dealList" :key="index">
							<view class="label-item" style="flex: 1;">{{index+1}}</view>
							<view class="label-item" style="flex: 0.8;">{{item.type == 'sell'?'受让':'转让'}}</view>
							<view class="label-item" style="justify-content:flex-end;flex: 0.8;">{{item.amount ||''}}&nbsp;&nbsp;&nbsp;&nbsp;</view>
							<view class="label-item" style="justify-content:flex-end;flex: 1.1;">{{item.price.toFixed(2)}}</view>
							<view class="label-item" style="flex: 3;font-size: 24upx;flex:3;">
								{{moment(item.time*1000).format('YYYY/MM/DD HH:mm:ss')}}
							</view>
						</view>
						<view class="msg" v-if="dealList.length>0">
							<image src="../../static/home/line.png" mode="widthFix" class="left-line"></image>
							<text class="text">没有更多内容啦</text>
							<image src="../../static/home/line.png" mode="widthFix" class="right-line"></image>
						</view>
					</view>
					<view v-show="dealList.length == 0" class="noListBox">
						<view class="noData">
							<image class="noDataImg" src="../../static/home/noData.png" mode=""></image>
							<view class="text">暂无数据</view>
						</view>
					</view>
				</view>
				<view class="contentItem" v-else-if="swiperCurrent == 1">
					<view v-html="billInfo.introduce"></view>
				</view>
				<view class="contentItem" v-else-if="swiperCurrent == 2">
					<view v-html="billInfo.details"></view>
				</view>
			</view>
		</view>
		<view class="bottom-btn">
			<view class="btn btn1" @tap="goTransaction(1)">转让</view>
			<view class="btn" @tap="goTransaction(0)">受让</view>
		</view>
	</view>
</template>

<script>
	import {
		PATH_IMG,
		BASE_API,
		WEBSOCKET_API
	} from '@/common/config.js';
	import uCharts from '@/common/u-charts.js';
	var uChartsInstance = {};
	import {
		newHistory,
		klinevtwoIndex,
		getByBillCode
	} from "@/api/home.js";
	import {
		mapState,
		mapMutations
	} from 'vuex';

	export default {
		data() {
			return {
				cWidth: 750,
				cHeight: 500,
				labelList: [{
						label: '1分钟',
						value: '1',
					},
					{
						label: '5分钟',
						value: '5',
					},
					{
						label: '15分钟',
						value: '15',
					},
					{
						label: '30分钟',
						value: '30',
					},
					{
						label: '1小时',
						value: '60',
					},
					{
						label: '日',
						value: '1D',
					},
					{
						label: '周',
						value: '1W',
					},
				],
				tabList: [{
					name: "成交"
				}, {
					name: "企业信息"
				}, {
					name: "项目信息"
				}],
				categoriesList: [], //k线图时间数据
				selectIndex: 5, //默认展示哪个时间段
				seriesData: [], //k线图对应数据
				swiperCurrent: 0,
				socketTask: null, //websocket echarts
				is_open_socket: false, //websocket是否开启
				socketTask1: null, //websocket 页面数据
				is_open_socket1: false, //websocket是否开启
				echartsInfoList: [], //图表数据
				coinCode: '', //代码
				interval: '1D', //图表时间段
				time: '', //推送时间戳
				infoData: {
					priceOpen : 100,
					priceHigh : 100,
					priceLow : 100
				},
				billCode: "", //积分代码
				billInfo: {}, //积分信息
				dealList: [], //成交列表
			};
		},
		onLoad(options) {
			console.log(options, '0000000');
			this.coinCode = options.coinCode;
			this.billCode = options.billCode
			this.getInfo();
			//这里的 750 对应 css .charts 的 width
			this.cWidth = uni.upx2px(750);
			//这里的 500 对应 css .charts 的 height
			this.cHeight = uni.upx2px(500);
			this.getData("1D")

		},
		methods: {
			goTransaction(msg) {
				console.log(msg,'跳转');
				uni.reLaunch({
					url: '/pages/transaction/index?coinCode=' + this.coinCode + '&billCode=' + this.billCode+ '&billName=' + this.billInfo.billName+'&tabBoxIndex=' + msg
				})
			},
			getInfo() {

				getByBillCode({
					billCode: this.billCode
				}).then(res => {
					console.log(res, '111')
					if (res.data.success) {
						let data = res.data.obj;
						if (data.details) {
							data.details = data.details.replace(
								/\<img /gi,
								'<img class="rich_pages" '
							)
						}
						if (data.introduce) {
							data.introduce = data.introduce.replace(
								/\<img /gi,
								'<img class="rich_pages" '
							)
						}
						this.billInfo = data;
						console.log(this.billInfo, '000000')
					}
				})
			},
			getServerData() {
				//模拟从服务器获取数据时的延时
				setTimeout(() => {
					//模拟服务器返回数据，如果数据格式和标准格式不同，需自行按下面的格式拼接
					let res = {
						categories: this.categoriesList,
						series: [{
							data: this.seriesData
						}]
					};
					this.drawCharts('kuKIifblofRczsEzZJYCFwSgPaTVnfqc', res);
				}, 500);
			},
			// goBack(){
			// 	uni.switchTab({
			// 		url:'/pages/transaction/index?'
			// 	})
			// },
			drawCharts(id, data) {
				const ctx = uni.createCanvasContext(id, this);
				uChartsInstance[id] = new uCharts({
					type: "candle",
					context: ctx,
					width: this.cWidth,
					height: this.cHeight,
					categories: data.categories,
					series: data.series,
					animation: true,
					rotate: false,
					rotateLock: false,
					background: "#FFFFFF",
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [5, 5, 0, 0],
					dataLabel: false,
					enableScroll: true,
					enableMarkLine: true,
					legend: {},
					xAxis: {
						labelCount: 2,
						itemCount: 40,
						disableGrid: true,
						gridColor: "#CCCCCC",
						gridType: "solid",
						dashLength: 2,
						scrollShow: false,
						scrollAlign: "right",
						scrollColor: "#A6A6A6",
						scrollBackgroundColor: "#EFEBEF",
						fontSize: 11,
					},
					yAxis: {
						data: [{
							type: "value",
							position: "right",
							fontSize: 11
						}]
					},
					extra: {
						candle: {
							color: {
								upLine: "#f04864",
								upFill: "#f04864",
								downLine: "#2fc25b",
								downFill: "#2fc25b"
							},
							average: {
								show: true,
								name: [
									"",
									"",
									""
								],
								day: [
									5,
									10,
									20
								],
								color: [
									"#ff00ff",
									"#238232",
									"#483943"
								]
							}
						},
						tooltip: {
							showCategory: true,
							borderRadius: 5,
							borderColor: '#000',
							borderOpacity: 1,
							bgColor: '#000',
							bgOpacity: .8,
							fontColor: '#fff',
							labelBgColor: '#000',
							labelFontColor: '#000'
						}
					}
				});
			},
			changeData(e) {
				this.selectIndex = e;
				let interval = this.labelList[e].value;
				// 初始化数据
				this.closeSocket(false);
				this.getData(interval);
				this.interval = interval;
			},
			getData(interval) {
				this.connectSocketInit({
					is_open_socket: true,
					init: true,
					cmd: 'req',
					coinCode: this.coinCode,
					interval
				})
				// 初始化表格数据
				this.getServerData();
				this.connectSocketInit2();
			},
			tabsChange(e) {
				this.swiperCurrent = e.index;
			},
			touchstart(e) {
				uChartsInstance[e.target.id].scrollStart(e);
			},
			touchmove(e) {
				uChartsInstance[e.target.id].dobuleZoom(e);
				uChartsInstance[e.target.id].scroll(e);
			},
			touchend(e) {
				uChartsInstance[e.target.id].scrollEnd(e);
				uChartsInstance[e.target.id].touchLegend(e);
				uChartsInstance[e.target.id].showToolTip(e);
			},
			back() {
				let canNavBack = getCurrentPages();
				if (canNavBack && canNavBack.length > 1) {
					uni.navigateBack({
						delta: 1
					});
				} else {
					history.back();
				};
			},
			// 进入这个页面的时候创建websocket连接【整个页面随时使用】(客户端)
			connectSocketInit(data) {
				let initObj = data;
				// is_open_socket,init,cmd,coinCode,interval
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					// url: "ws://192.168.63.105:8111/deep", // 你的socket地址
					url: WEBSOCKET_API + "/deep",
					success(res) {
						console.log("websocket连接成功", res);
					},
				});
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					this.is_open_socket = initObj.is_open_socket;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					// 初始化数据
					this.socketTask.send({
						data: JSON.stringify({
							"cmd": initObj.cmd,
							"timeout": "1440",
							"coinCode": initObj.coinCode,
							"interval": initObj.interval
						}),
						async success() {
							console.log("消息发送成功");
						},
					});

					// 再开启
					this.sendMessage('sub', this.coinCode, initObj.interval);
					//
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						if (JSON.parse(res.data).type == 'one') {
							// 初始化先清除数据
							this.echartsInfoList = [];
							this.categoriesList = [];
							this.seriesData = [];
							this.time = "";
							// console.log("收到服务器内容：", JSON.parse(res.data));
							this.echartsInfoList.push(JSON.parse(res.data));
							// 保存初始化最后一个数据时间戳;
							this.time = this.echartsInfoList[0].data[this.echartsInfoList[0].data.length -
								1].id * 1000;
							this.echartsInfoList[0].data.forEach((item, index) => {
								if (this.selectIndex == 5 || this.selectIndex == 6) {
									this.categoriesList.push(this.moment(parseInt(item.id * 1000))
										.format('YYYY/MM/DD'))
								} else {
									this.categoriesList.push(this.moment(parseInt(item.id * 1000))
										.format('YYYY/MM/DD HH:mm'))
								}
								this.seriesData.push([item.open, item.close, item.low, item.high]);
							})
							// console.log(this.categoriesList,this.seriesData)
						} else {
							let data = JSON.parse(res.data).data;
							// 判断推送时间节点是否和初始化最后一个时间点相同；相等视图不重新渲染。反之更新视图
							if (this.time == (data.id * 1000)) {
								this.time = data.id * 1000;
								// this.seriesData.push([data.open, data.close, data.low, data.high]);
								return;
							} else {
								if (this.selectIndex == 5 || this.selectIndex == 6) {
									this.categoriesList.push(this.moment(parseInt(data.id * 1000)).format(
										'YYYY/MM/DD'));
									this.time = data.id * 1000
								} else {
									this.categoriesList.push(this.moment(parseInt(data.id * 1000)).format(
										'YYYY/MM/DD HH:mm'));
									this.time = data.id * 1000
								}
								this.seriesData.push([data.open, data.close, data.low, data.high]);
							}
						}
					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					// console.log("已经被关闭了")
				})
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket(is_open_socket) {
				const _this = this
				this.socketTask.close({
					success(res) {
						console.log("关闭成功", res)
						_this.is_open_socket = is_open_socket
					},
					fail(err) {
						// console.log("关闭失败", err)
					}
				})
			},
			// 发送消息
			sendMessage(cmd, coinCode, interval) {
				this.socketTask.send({
					data: JSON.stringify({
						"cmd": cmd,
						"coinCode": coinCode,
						"interval": interval
					}),
					async success() {
						// console.log("消息发送成功");
					},
				});
			},
			// 进入这个页面的时候创建websocket连接【整个页面随时使用】(客户端)
			connectSocketInit2(data) {
				// this.$refs.min_loading.open('加载中，请稍后！');
				// is_open_socket,init,cmd,coinCode,interval
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask1 = uni.connectSocket({
					// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
					// url: "ws://192.168.63.105:8111/deep", // 你的socket地址
					url: WEBSOCKET_API + "/deep/deep",
					success(res) {
						console.log("websocket连接成功", res);
					},
				});
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask1.onOpen((res) => {
					this.is_open_socket1 = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					// 初始化数据
					this.sendMessage2();
					//
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask1.onMessage((res) => {
						let list = [];
						list = JSON.parse(res.data).buySellData;
						list.forEach(item => {
							let symbolId = item.symbolId.split("_")[0];
							if (symbolId == this.billCode) {
								let data = item.payload.marketTrades.trades;
								let infoObj = item.payload;
								infoObj.priceOpen = Number(infoObj.priceOpen).toFixed(2);
								infoObj.priceHigh = Number(infoObj.priceHigh).toFixed(2);
								infoObj.priceLow = Number(infoObj.priceLow).toFixed(2);					
								this.infoData = infoObj;
								this.dealList = [...data];
							}
						})
						// this.$refs.min_loading.close();

					});
					// this.$refs.min_loading.close();
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					// console.log("已经被关闭了");
					// this.$refs.min_loading.close();
				})
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket2(is_open_socket) {
				const _this = this
				this.socketTask1.close({
					success(res) {
						console.log("关闭成功", res)
						_this.is_open_socket1 = false
					},
					fail(err) {
						// console.log("关闭失败", err)
					}
				})
			},
			// 发送消息 页面数据信息
			sendMessage2() {
				this.socketTask1.send({
					data: JSON.stringify({
						"cmd": "trading",
						"coinCode": this.coinCode,
						"type": '0',
						"timeout": 1440
					}),
					async success() {
						// console.log("消息发送成功");
					},
				});
			},
		},
		onHide() {
			this.closeSocket(false);
			this.closeSocket2(false);
		},
		onUnload() {
			this.closeSocket(false);
			this.closeSocket2(false);
		}
	};
</script>

<style lang="scss" scoped>
	page {
		width: 100%;
		height: 100%;
		background-color: #fff;
		// content-visibility: auto;
		// contain-intrinsic-size: 1px 5000px;
	}

	.container {
		width: 100%;
		height: 100%;
		padding-top: 120upx;

		.homeBg {
			width: 100%;
			height: 120upx;
			background: url(../../static/login/bg.png) no-repeat top center;
			background-size: 100% 500%;
			position: fixed;
			top: 0;
			left: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			z-index: 20;

			.icon-left {
				position: absolute;
				left: 42upx;
				// bottom: 50upx;
				top: 50%;
				transform: translateY(-50%);
			}

			.title {
				font-size: 32upx;
				font-family: PingFang SC;
				font-weight: bold;
				color: #FFFFFF;
			}

			.searchIcon {
				width: 44upx;
				position: absolute;
				right: 42upx;
				// bottom: 50upx;
				top: 50%;
				transform: translateY(-50%);
			}
		}

		.billInfo {
			font-size: 30upx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #333;
			padding: 30upx;

			.issues {
				margin-bottom: 10upx;
			}

			.price {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding-top: 20upx;

				.price-item {
					width: 45%;
					padding: 20upx 0;
					background-color: #F5F5F5;
					border-radius: 8upx;
					text-align: center;
					color: #7D7D7D;

					.priceNum {
						font-weight: bold;
						color: #333;
					}
				}

				.active {
					background-color: #5DB1FF;
					color: #D9EDFF;

					.priceNum {
						font-weight: bold;
						color: #fff;
					}
				}
			}

			.quotation {
				display: flex;
				align-items: center;
				justify-content: space-between;
				text-align: center;
				font-size: 24upx;
				padding-top: 40upx;

				.value {
					padding-top: 10upx;
				}
			}
		}

		.line {
			width: 100%;
			height: 20upx;
			background: #F6F7F9;
		}

		.situation {
			width: 100%;
			padding: 30upx;
			font-size: 28upx;
			font-family: PingFang SC;
			font-weight: 500;
			color: #333;

			.top {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.bottom {
				padding-top: 20upx;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}

		.label {
			display: flex;
			align-items: center;
			padding: 0 30upx;

			.label-item {
				font-size: 26upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #B0B5BC;
				line-height: 50upx;
				margin-right: 20upx;
			}

			.activeClass {
				color: #000;
				font-weight: bold;
			}
		}

		.enterpriseInfo {
			width: 100%;
			padding: 0 30upx;

			.bottomContent {
				width: 100%;
				padding-bottom: 100upx;

				.contentItem {
					width: 100%;
					font-family: PingFang SC;
					font-weight: 500;
					color: #333;
					font-size: 28upx;
					padding-top: 10upx;
					border-top: 2upx solid #333;

					.tabLabel {
						display: flex;
						align-items: center;
						justify-content: center;

						.label-item {
							flex: 1;
							display: flex;
							align-items: center;
							justify-content: center;
						}

					}

					.tabLabel1 {
						.label-item {
							line-height: 70upx;
						}
					}

					.msg {
						text-align: center;
						font-size: 24upx;
						font-family: PingFang SC;
						font-weight: 500;
						color: #BCBCBC;
						margin-top: 30upx;
						display: flex;
						align-items: center;
						justify-content: center;

						.text {
							margin: 0 20upx;
						}

						.left-line {
							width: 100upx;
						}

						.right-line {
							width: 100upx;
							transform: rotate(-180deg);
						}

						// padding-bottom: 100upx;
					}

					.noListBox {
						text-align: center;

						.noData {
							width: 100%;
							display: flex;
							align-items: center;
							justify-content: center;
							flex-direction: column;
							margin-top: 200upx;

							.noDataImg {
								width: 316upx;
								height: 126upx;
							}

							.text {
								font-size: 26upx;
								font-family: PingFang SC;
								font-weight: 500;
								color: #B0B5BC;
								line-height: 92upx;
							}
						}
					}
				}
			}
		}
	}

	.charts {
		width: 750upx;
		height: 500upx;
	}

	.bottom-btn {
		width: 100%;
		position: fixed;
		bottom: 0;
		left: 0;
		background-color: #fff;
		padding: 10upx 30upx;
		display: flex;
		align-items: center;
		justify-content: space-between;

		.btn {
			width: 49%;
			height: 70upx;
			background: #039E04;
			border-radius: 4upx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 30upx;
			font-family: PingFang SC;
			font-weight: 400;
			color: #FFFFFF;
		}

		.btn1 {
			background: #c20707;
		}
	}
</style>
